#include "uart.h"
#include "../../sensor_check/sensor.h"

// 从Serial中特定条目后获取字符串 直到空格或\n 警告:该方法仅适合多次小片段 过大的片段可能导堵塞时间过长
String Serial_uart::get_string(String chr)
{
    static const char null[2] = {0};
    if (!serial_ok())
        return "Not";
    String _rx_buffer;
    const String _chr = chr;
    _rx_buffer = serial_read();
    serial_clean();
    const uint16_t size = _strlen(_rx_buffer);
    const uint8_t chr_size = _strlen(_chr);

    // DEBUG
    /*
    uart.uart_ok("GET:");
    char debug_char[2] = {0};
    for (uint16_t debug = 0; debug < size; debug++) {
        debug_char[0] = _rx_buffer[debug];
        uart.uart_ok(debug_char);
    }
    */

    for (uint16_t c = 0; c < size; c++)
    {
        if (_rx_buffer[c] == _chr[0])
        {
            for (uint16_t a = 0; a < chr_size; a++)
            {
                if (!(_rx_buffer[c + a] == _chr[a]))
                    return null;
            }

            // DEBUG
            // uart.uart_ok("GET_ARR");
            uint16_t array_int = size - (c + chr_size);
            char callback[array_int + 1] = {'\n'};
            char get;
            for (uint16_t g = 0; g < array_int; g++)
            {
                get = _rx_buffer[c + chr_size + g];
                if (get != '\n' && get != ' ' && get != 0)
                    callback[g] = get;
            }
            return (String)callback;
        }
    }

    // DEBUG
    uart.send("BAD");

    return null;
}

// 从字符串中获取int32
// 返回: int
// failed no_len : -100000000
//        not_int : -200000000
int32_t Serial_uart::get_int(String array)
{
    if (!(_strlen(array) > 0))
        return -100000000;
    String _get = array;
    const uint8_t len = _strlen(_get);
    char get[len] = {'\n'};

    for (uint16_t scan = 0; scan < len; scan++)
    {
        if ((_get[scan] < '0' || _get[scan] > '9') && _get[scan] != '-')
        {
            if (scan == len - 1)
                break;
            return -200000000;
        }
        get[scan] = _get[scan];
    }
    return atoi(get);
}

// 获取绑定触摸区域的物理TOUCH ID
uint8_t Serial_uart::get_tsm12_id(uint8_t packet) {
    uint8_t get_packet = packet;
    for (uint8_t gtt = 0; gtt < TOUCH_NUM; gtt++) {
        for (uint8_t gt2 = 0; gt2 < 2; gt2++) {
            if (get_packet == sensor.mai_map[gtt][gt2])
                return gtt;
        }
    }
    return 255;
    
}